package main

import (
	"bufio"
	"encoding/json"
	"log"
	"net"

	aop "gitee.com/jnshao/go-start/pattern/ch04/aop/core"
)

// 责任链模式 - 行为模式
/*
发起一个请求， 我不管应该找谁来负责， 交给我的leader， 由leader自己去找应该发给谁， 职责链
*/
// gin的中间件采用的是责任链模式

func main() {
	listener, err := net.Listen("tcp", ":8080")
	log.Printf("server listening on :%s", listener.Addr())
	if err != nil {
		log.Printf("server listen tcp err:%v", err)
		panic(err)
	}
	defer listener.Close()
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("connection tcp accept err:%v", err)
			panic(err)
		}

		go func() {
			content := &aop.Content{Code: "ok", Msg: ""}
			aopEngine := aop.NewEngine(func() { handle(conn, content) })
			aopEngine.Use(func(ctx *aop.Context) {
				log.Printf("method one starting...")
				content.Msg += "method one run->"
				ctx.Next()
				log.Printf("method one ending...")
			})
			aopEngine.Use(func(ctx *aop.Context) {
				log.Printf("method two starting...")
				content.Msg += "method two run->"
				ctx.Next()
				log.Printf("method two ending...")
			})
			aopEngine.Use(func(ctx *aop.Context) {
				log.Printf("method three starting...")
				content.Msg += "method three run->"
				log.Printf("method three ending...")
				//ctx.Next()

			})
			aopEngine.Use(func(ctx *aop.Context) {
				log.Printf("method four starting...")
				ctx.Abort()
				// ctx.Content.Code = "err"
				content.Msg += "method four run->"
				log.Printf("method four ending...")
			})
			aopEngine.Run()
		}()
	}
}

func handle(conn net.Conn, content *aop.Content) error {
	defer conn.Close()
	log.Printf("handle starting...")
	writer := bufio.NewWriter(conn)
	content.Msg += "hello world!"
	bytes, _ := json.Marshal(*content)
	n, err := writer.Write(bytes)
	writer.Flush()
	if err != nil {
		log.Printf("write string err:%v", err)
		return err
	}
	log.Printf("handle ending...,write bytes len :%v", n)
	return nil
}
